package com.stenio.fancat.service.wx;

import com.stenio.fancat.util.AccessToken;
import com.stenio.fancat.common.TemplateData;
import com.stenio.fancat.vo.WxMssVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class WxPushServiceQcl {
    //用来请求微信的get和post
    private RestTemplate restTemplate = new RestTemplate();

    @Value("${templatePic}")
    private String templatePic;

    /**
     * 微信小程序推送单个用户
     * @param openid
     * @param formid
     * @param templateId   这个是模板消息的id，微信小程序后台有这个id
     * @param params
     * @return
     */
    public String pushOneUser(String openid, String formid,String templateId,String[] params){


        //获取access_token
        String access_token = null;
        try {
            access_token = AccessToken.getAccessToken("wx164861672633ebee","2296163e67268b39e48acac7495d0b91");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send" +
                "?access_token=" + access_token;

        //拼接推送的模版
        WxMssVo wxMssVo = new WxMssVo();
        wxMssVo.setTouser(openid);//用户openid
        wxMssVo.setTemplate_id(templateId);//模版id
        wxMssVo.setForm_id(formid);//formid

        Map<String, TemplateData> m = new HashMap<>(5);

        TemplateData keyword1 = new TemplateData();
        keyword1.setValue(params[0]);
        m.put("keyword1", keyword1);

        TemplateData keyword2 = new TemplateData();
        keyword2.setValue(params[1]);
        m.put("keyword2", keyword2);
        wxMssVo.setData(m);

        TemplateData keyword3 = new TemplateData();
        keyword3.setValue(params[2]);
        m.put("keyword3", keyword3);
        wxMssVo.setData(m);

        TemplateData keyword4 = new TemplateData();
        keyword4.setValue(params[3]);
        m.put("keyword4", keyword4);
        wxMssVo.setData(m);

        TemplateData keyword5 = new TemplateData();
        keyword5.setValue(params[4]);
        m.put("keyword5", keyword5);
        wxMssVo.setData(m);

        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, wxMssVo, String.class);
        System.out.println(responseEntity.getBody());
        return responseEntity.getBody();
    }

}
